package pers.xiaojun.boot.web.core.util;

import cn.hutool.extra.servlet.JakartaServletUtil;
import cn.hutool.json.JSONUtil;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.http.MediaType;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import java.nio.charset.StandardCharsets;
import java.util.Objects;

/**
 * Servlet 工具类
 *
 * @author xiaojun
 * @since 2025-10-04
 */

public class ServletUtils {

    /**
     * 响应 JSON 数据
     *
     * @param response 响应对象
     * @param content  响应内容
     */
    public static void writeJSON(HttpServletResponse response, Object content) {
        String contentJSON = JSONUtil.toJsonStr(content);
        response.setCharacterEncoding(StandardCharsets.UTF_8.name());
        JakartaServletUtil.write(response, contentJSON, MediaType.APPLICATION_JSON_VALUE);
    }

    /**
     * 获取当前 HttpServletRequest 对象
     *
     * @return {@link HttpServletRequest}
     */
    public static HttpServletRequest getRequest() {
        // 提前判空
        RequestAttributes requestAttributes = Objects.requireNonNull(RequestContextHolder.getRequestAttributes());
        return ((ServletRequestAttributes) requestAttributes).getRequest();
    }

    /**
     * 获取请求客户端Ip地址
     *
     * @return IP地址
     */
    public static String getClientIp() {
        HttpServletRequest request = getRequest();
        return request.getRemoteAddr();
    }


}